package info.zlong.visibleruntime.core.mongo;

import java.util.HashMap;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;
import info.zlong.visibleruntime.core.model.LogMsg;

public class MongoConnector {
    
    private Mongo mongo;
	
	public MongoConnector(String hosts,String userName,String password,String databaseName,String collectionName){
		mongo = new Mongo(hosts, userName, password, databaseName, collectionName);
	}
	
	public void open(){
		mongo.open();
		
	}
	
	public void update(LogMsg logMsg){
		String id = logMsg.getId();
		int type = logMsg.getType();
		String path = logMsg.getPath();
		if(path == null || path.length() < 1) path = "nokey";
		long time = logMsg.getTime();
		String msg = logMsg.getMsg();
		
		if(type == LogMsg.START){

			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("_startTime", time);
			map.put("_startMsg", msg);
			
			update(id, path, map,time);
		}else if(type == LogMsg.END){

			update(id, path+"._endTime", time,time);
//			update(id, path+"._endMsg", msg);
			
		}
	}
	
	private void update(String id,String key,Object value,long time){
		//db.users.update({"name":"zlong"}, {$set:{"name":"zlong","k1.k2.k3":{"k4":"v4"}}}, {upsert:true});
		BasicDBObject query = new BasicDBObject();
		query.put("_id", id);

		BasicDBObject obj = new BasicDBObject();
		HashMap<String,Object> map = new HashMap<String,Object>();
		obj.put("$set",map);
		
		map.put("_endTime", time);
		map.put(key, value);
		
		//更新
		UpdateResult result = mongo.getCollection().updateOne(query, obj);
		if(result.getMatchedCount() < 1){
			
			map.put("_startTime", time);	//添加创建时间
			mongo.getCollection().updateOne(query, obj,new UpdateOptions().upsert(true));
		}
		
	}
	
	public void close(){
		mongo.close();
	}
}
